package com.farm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.farm.entity.User;
import com.farm.service.UserService;

@Controller
public class ProfileController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/profile")
    public String showProfile(@AuthenticationPrincipal User user, Model model) {
        model.addAttribute("user", user);
        return "profile";
    }

    @PostMapping("/profile/update")
    public String updateProfile(
            @AuthenticationPrincipal User user,
            @RequestParam String realName,
            @RequestParam String phone,
            @RequestParam String address,
            RedirectAttributes redirectAttributes) {
        try {
            user.setRealName(realName);
            user.setPhone(phone);
            user.setAddress(address);
            userService.updateUser(user);
            redirectAttributes.addFlashAttribute("success", "个人信息更新成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新失败：" + e.getMessage());
        }
        return "redirect:/profile";
    }

    @PostMapping("/profile/password")
    public String updatePassword(
            @AuthenticationPrincipal User user,
            @RequestParam String oldPassword,
            @RequestParam String newPassword,
            @RequestParam String confirmPassword,
            RedirectAttributes redirectAttributes) {
        try {
            // 验证旧密码
            if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
                throw new RuntimeException("旧密码不正确");
            }
            
            // 验证新密码
            if (!newPassword.equals(confirmPassword)) {
                throw new RuntimeException("两次输入的新密码不一致");
            }
            
            // 更新密码
            user.setPassword(passwordEncoder.encode(newPassword));
            userService.updateUser(user);
            redirectAttributes.addFlashAttribute("success", "密码修改成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "密码修改失败：" + e.getMessage());
        }
        return "redirect:/profile";
    }
} 